package com.jwt;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;

import java.text.SimpleDateFormat;
import java.util.Date;

public class ParseJwt {

    public static void main(String[] args){
        // 解析 jwt 无时限设定
        // parse_jwt_time_nolimit();
        // 解析 jwt 有过期时间
        parse_jwt_time_limit();

    }

    protected static void parse_jwt_time_nolimit() {
        String jwtToken = "eyJhbGciOiJIUzI1NiJ9.eyJqdGkiOiI2NjY2Iiwic3ViIjoiY2FybCIsImlhdCI6MTU0NjEwMTg5NX0.jMtLeI0g7uC5S6QJHxtVBFNAm0oS4jk4WyjflOY0vLU" ;
        Claims claims = Jwts.parser().setSigningKey("ten_square").parseClaimsJws(jwtToken).getBody();
        System.out.println(" subject : " + claims.getSubject());
        System.out.println(" issueAt : " + claims.getIssuedAt());
        System.out.println(" id : " + claims.getId());
    }

    protected static void parse_jwt_time_limit() {
        String jwtToken = "eyJhbGciOiJIUzI1NiJ9.eyJqdGkiOiI3NzciLCJzdWIiOiJqYWNrIiwiaWF0IjoxNTQ2MTg4MTc2LCJleHAiOjE1NDYxODgzNTUsInJvbGUiOiJhZG1pbiJ9.y5F9BTt0ern8oIOcHRDYuNc-CdP4JvlmcE_qFZnNlkQ" ;
        Claims claims = Jwts.parser().setSigningKey("ten_square").parseClaimsJws(jwtToken).getBody();
        System.out.println(" id : " + claims.getId());
        System.out.println(" subject : " + claims.getSubject());
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
        Date expirationTime = claims.getExpiration();
        Date issueAtTime = claims.getIssuedAt();

        System.out.println(" issueAt : " + format.format(issueAtTime));
        System.out.println(" expiration : " + format.format(expirationTime));
        System.out.println(" nowTime : " + format.format(new Date()));

        String role = claims.get("role").toString();
        System.out.println(" role  : " + role);

    }

}
